﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using B10.Models;
using B10.Helpers;
using ManagedFusion.Web;
using Facebook;

namespace B10.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {

        // This constructor is used by the MVC framework to instantiate the controller using
        // the default forms authentication and membership providers.
        public AccountController()
            : this(null, null, null, null)
        {
        }

        // This constructor is not used by the MVC framework but is instead provided for ease
        // of unit testing this type. See the comments in AccountModels.cs for more information.
        public AccountController(IFormsAuthenticationService formsService,
            IMembershipService membershipService, IProfileService profileService,
            IEmailService emailService)
        {
            FormsService = formsService ?? new FormsAuthenticationService();
            MembershipService = membershipService ?? new AccountMembershipService();
            ProfileService = profileService ?? new ProfileService();
            EmailService = emailService ?? new EmailService();
        }

        public IEmailService EmailService
        {
            get;
            private set;
        }

        public IProfileService ProfileService
        {
            get;
            private set;
        }

        public IFormsAuthenticationService FormsService
        {
            get;
            private set;
        }

        public IMembershipService MembershipService
        {
            get;
            private set;
        }

        protected override void Initialize(RequestContext requestContext)
        {
            if (requestContext.HttpContext.User.Identity is WindowsIdentity)
            {
                throw new InvalidOperationException("Windows authentication is not supported.");
            }
            else
            {
                base.Initialize(requestContext);
            }
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;

            base.OnActionExecuting(filterContext);
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        public ActionResult LogOff()
        {
            if (!FacebookConnect.IsConnected)
            {
                FormsService.SignOut();
            }
            return RedirectToAction("Index", "Home");
        }

        public ActionResult LogOn()
        {
            return View();
        }

        public ActionResult FacebookLogOn(string returnUrl, string token, long userId)
        {
            //if (FacebookConnect.IsConnected)
            //{
            //    Facebook.FacebookAPI api = new Facebook.FacebookAPI(FacebookConnect.AccessToken);
            //    Facebook.JSONObject me = api.Get("/" + FacebookConnect.UserID);
            //    if (me != null)
            //    {
            //        //FormsService.SignIn(me.Dictionary["name"].String,true);
            //    }
            //}
            FacebookConnect.Init(token, userId);
            if (!String.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public ActionResult FacebookLogOff(string returnUrl)
        {
            FacebookConnect.Terminate();
            if (!String.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        [HttpPost]
        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
            Justification = "Needs to take same parameter type as Controller.Redirect()")]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    UserProfile profile = ProfileService.GetProfile(model.UserName);
                    if (profile != null)
                    {
                        FormsService.SignIn(profile.Id.ToString(), model.RememberMe);
                        if (!String.IsNullOrEmpty(returnUrl))
                        {
                            return Redirect(returnUrl);
                        }
                        else
                        {
                            return RedirectToAction("Index", "Home");
                        }
                    }
                }
                else
                {
                    MembershipUser user = MembershipService.GetUser(model.UserName);
                    if (user != null && !user.IsApproved)
                    {
                        return RedirectToAction("Verify", new { id = model.UserName });
                    }
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult Register()
        {
            return View();
        }

        [CaptchaValidation]
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService
                    .CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    ProfileService.CreateNewProfile(model.UserName);
                    EmailService.SendVerificationEmail(
                        MembershipService.GetUser(model.UserName), Request.Url.Authority);
                    return RedirectToAction("Verify", new { id = model.UserName });
                    //FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    //return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult Verify(object id)
        {
            return View(id);
        }

        [HttpPost]
        public ActionResult Verify(string id, FormCollection collection)
        {
            if (!String.IsNullOrEmpty(id))
            {
                MembershipUser user = MembershipService.GetUser(id);
                if (user != null && !user.IsApproved)
                {
                    ModelState.Clear();
                    EmailService.SendVerificationEmail(
                                MembershipService.GetUser(id), Request.Url.Authority);
                    return PartialView("Info", new InfoItem("Email został wysłany!"));
                }
            }
            return null;
        }

        public ActionResult VerifyEmail(string id)
        {
            Guid guid = new Guid(id);
            string userName;
            if (MembershipService.ActivateUser(guid, out userName))
            {
                return View("Verified");
                //FormsService.SignIn(userName, false /* createPersistentCookie */);
            }
            else
            {
                // Wrong GUID or user was already approved
            }
            return RedirectToAction("Index", "Home");
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }

    }
}
